var levels = new LevelSet('levels');

function addLevels() {
  levels.addLevel("Welcome", "level0/welcome.html", "level0/welcome.js");
  levels.addLevel("New car", "games/race/cars/newcar.html", "games/race/cars/newcar.js");
  levels.addLevel("Move car", "games/race/cars/movecar.html", "games/race/cars/movecar.js");
  levels.addLevel("Driving", "games/race/controls/move-rel.html", "games/race/controls/move-rel.js");
  levels.addLevel("Course", "games/race/course/course.html", "games/race/course/course.js");
  //  levels.addLevel("Course Abs", "games/race/course/course-abs.html", "games/race/course/course-abs.js");
  levels.addLevel("Collision detection", "games/race/collision/collisions.html", "games/race/collision/collisions.js");
  //  levels.addLevel("Complete Game", "games/race/complete/complete.html", "games/race/complete/complete.js");
  levels.start();
}

function Level(description, notes, src) {
  this.description = description;
  this.notes = notes;
  this.src = src;
}

Level.prototype.load = function(runIt) {
  this.loadSrc(runIt);
  this.loadNotes();
};

Level.prototype.loadSrc = function(runIt) {
  google.maps.DownloadUrl(this.src, function(data, responseCode) {
                            if (data) {
                              el("code").value = data;
                              if (runIt) {
                                runCode();
                                log("Loaded: " + this.src);
                              }
                            }
                          });
};

Level.prototype.loadNotes = function() {
  google.maps.DownloadUrl(this.notes, function(data, responseCode) {
                            if (data) {
                              el("notes").innerHTML = data;
                            }
                          });
};

function LevelSet(name) {
  this.name = name;
  this.levels = [];
  this.curLevel = 0;
}

LevelSet.prototype.addLevel = function(description, notes, src) {
  this.levels.push(new Level(description, notes, src));
};

LevelSet.prototype.start = function() {
  this.curLevel = 0;
  this.levels[0].load(false);
  this.syncArrows();
};

LevelSet.prototype.lastLevel = function() {
  if (this.curLevel <= 0)
    return;
  reset();
  this.curLevel--;
  this.levels[this.curLevel].load(false);
  this.syncArrows();
};

LevelSet.prototype.nextLevel = function() {
  if (this.curLevel >= this.levels.length - 1)
    return;
  reset();
  this.curLevel++;
  this.levels[this.curLevel].load(false);
  this.syncArrows();
};

LevelSet.prototype.syncArrows = function() {
  var e = el('levelArrows');
  e.innerHTML = '';
  if (this.curLevel > 0) {
    e.innerHTML += '<a href="javascript:' + this.name +
      '.lastLevel();void(0);" class="syncArrow">&lt; Last</a>';
  }
  if (this.curLevel < this.levels.length - 1) {
    e.innerHTML += ' <a href="javascript:' + this.name +
      '.nextLevel();void(0);" class="syncArrow">Next &gt;</a>';
  }
};
